<template>
  <div class="settings">
    <el-card class="app-card">
      <template #header>
        <div class="card-header">
          <span>设置</span>
        </div>
      </template>
      
      <el-form label-position="top">
        <el-divider>基础设置</el-divider>
        
        <!-- Chrome路径设置 -->
        <el-form-item label="Chrome可执行文件路径">
          <el-row :gutter="20">
            <el-col :span="18">
              <el-input v-model="settings.chromePath" readonly />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="selectChromePath">
                <el-icon><i-ep-folder-opened /></el-icon>
                选择文件
              </el-button>
            </el-col>
          </el-row>
          <div class="form-hint">若留空，将使用系统默认Chrome路径</div>
        </el-form-item>
        
        <!-- 默认数据目录设置 -->
        <el-form-item label="默认用户数据目录">
          <el-row :gutter="20">
            <el-col :span="18">
              <el-input v-model="settings.defaultUserDataDir" readonly />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="selectUserDataDir">
                <el-icon><i-ep-folder /></el-icon>
                选择目录
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        
        <!-- 默认快捷方式目录设置 -->
        <el-form-item label="默认快捷方式保存目录">
          <el-row :gutter="20">
            <el-col :span="18">
              <el-input v-model="settings.defaultShortcutDir" readonly />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="selectShortcutDir">
                <el-icon><i-ep-document /></el-icon>
                选择目录
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-divider>窗口设置</el-divider>
        
        <!-- 默认窗口大小 -->
        <el-form-item label="默认窗口大小">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="宽度">
                <el-input-number v-model="settings.defaultWidth" :min="400" :max="3840" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="高度">
                <el-input-number v-model="settings.defaultHeight" :min="300" :max="2160" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        
        <!-- 默认窗口间距 -->
        <el-form-item label="默认窗口间距">
          <el-input-number v-model="settings.defaultSpacing" :min="0" :max="100" />
        </el-form-item>
        
        <el-divider>快捷键设置</el-divider>
        
        <!-- 快捷键设置 -->
        <el-form-item label="快捷键">
          <el-table :data="hotkeysData" style="width: 100%">
            <el-table-column prop="action" label="操作" min-width="200" />
            <el-table-column prop="key" label="快捷键" min-width="150">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.key" 
                  placeholder="输入快捷键"
                  @focus="startCaptureShortcut(scope.$index)"
                  @blur="stopCaptureShortcut"
                  readonly
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="resetHotkey(scope.$index)"
                >
                  重置
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        
        <el-divider>其他设置</el-divider>
        
        <!-- 自动启动Chrome -->
        <el-form-item>
          <el-checkbox v-model="settings.autoStartChrome">创建环境后自动启动Chrome</el-checkbox>
        </el-form-item>
        
        <!-- 记住窗口位置 -->
        <el-form-item>
          <el-checkbox v-model="settings.rememberWindowPositions">记住窗口位置和大小</el-checkbox>
        </el-form-item>
        
        <!-- 自动检查更新 -->
        <el-form-item>
          <el-checkbox v-model="settings.checkUpdates">启动时自动检查更新</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
          <el-button @click="resetSettings">恢复默认设置</el-button>
          <el-button @click="exportSettings">导出设置</el-button>
          <el-button @click="importSettings">导入设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 快捷键捕获对话框 -->
    <el-dialog
      v-model="shortcutDialogVisible"
      title="设置快捷键"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="shortcut-capture">
        <p>请按下要设置的快捷键组合</p>
        <p class="shortcut-preview">{{ shortcutPreview }}</p>
        <p class="shortcut-hint">提示：支持 Ctrl、Shift、Alt 组合键</p>
      </div>
      <template #footer>
        <el-button @click="cancelShortcutCapture">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { FolderOpened, Folder, Document } from '@element-plus/icons-vue'

// 使用别名以避免命名冲突
const iEpFolderOpened = FolderOpened
const iEpFolder = Folder
const iEpDocument = Document

interface SettingType {
  chromePath: string
  defaultUserDataDir: string
  defaultShortcutDir: string
  defaultWidth: number
  defaultHeight: number
  defaultSpacing: number
  autoStartChrome: boolean
  rememberWindowPositions: boolean
  checkUpdates: boolean
  hotkeys: {
    [key: string]: string
  }
}

interface HotkeyItem {
  action: string
  key: string
  actionKey: string
}

// 应用设置
const settings = reactive<SettingType>({
  chromePath: '',
  defaultUserDataDir: '',
  defaultShortcutDir: '',
  defaultWidth: 1024,
  defaultHeight: 768,
  defaultSpacing: 10,
  autoStartChrome: true,
  rememberWindowPositions: true,
  checkUpdates: true,
  hotkeys: {
    importWindows: 'Ctrl+I',
    closeAllWindows: 'Ctrl+Shift+C',
    arrangeWindows: 'Ctrl+Shift+A',
    startSync: 'Ctrl+Shift+S',
    stopSync: 'Ctrl+Shift+X'
  }
})

// 快捷键数据
const hotkeysData = ref<HotkeyItem[]>([
  { action: '导入窗口', key: settings.hotkeys.importWindows, actionKey: 'importWindows' },
  { action: '关闭所有窗口', key: settings.hotkeys.closeAllWindows, actionKey: 'closeAllWindows' },
  { action: '排列窗口', key: settings.hotkeys.arrangeWindows, actionKey: 'arrangeWindows' },
  { action: '开始同步', key: settings.hotkeys.startSync, actionKey: 'startSync' },
  { action: '停止同步', key: settings.hotkeys.stopSync, actionKey: 'stopSync' }
])

// 快捷键捕获相关
const shortcutDialogVisible = ref(false)
const shortcutPreview = ref('')
const currentHotkeyIndex = ref(-1)
const capturingShortcut = ref(false)

// 选择Chrome路径
const selectChromePath = async () => {
  try {
    const path = await window.electronAPI.selectChromeExecutable()
    if (path) {
      settings.chromePath = path
    }
  } catch (error) {
    console.error('选择Chrome路径失败:', error)
    ElMessage.error('选择Chrome路径失败')
  }
}

// 选择用户数据目录
const selectUserDataDir = async () => {
  try {
    const path = await window.electronAPI.selectDirectory()
    if (path) {
      settings.defaultUserDataDir = path
    }
  } catch (error) {
    console.error('选择目录失败:', error)
    ElMessage.error('选择目录失败')
  }
}

// 选择快捷方式目录
const selectShortcutDir = async () => {
  try {
    const path = await window.electronAPI.selectDirectory()
    if (path) {
      settings.defaultShortcutDir = path
    }
  } catch (error) {
    console.error('选择目录失败:', error)
    ElMessage.error('选择目录失败')
  }
}

// 开始捕获快捷键
const startCaptureShortcut = (index: number) => {
  currentHotkeyIndex.value = index
  shortcutDialogVisible.value = true
  shortcutPreview.value = ''
  capturingShortcut.value = true
}

// 停止捕获快捷键
const stopCaptureShortcut = () => {
  capturingShortcut.value = false
}

// 取消快捷键捕获
const cancelShortcutCapture = () => {
  shortcutDialogVisible.value = false
  stopCaptureShortcut()
}

// 重置快捷键
const resetHotkey = (index: number) => {
  const defaultHotkeys: { [key: string]: string } = {
    importWindows: 'Ctrl+I',
    closeAllWindows: 'Ctrl+Shift+C',
    arrangeWindows: 'Ctrl+Shift+A',
    startSync: 'Ctrl+Shift+S',
    stopSync: 'Ctrl+Shift+X'
  }
  
  const actionKey = hotkeysData.value[index].actionKey
  hotkeysData.value[index].key = defaultHotkeys[actionKey]
  settings.hotkeys[actionKey] = defaultHotkeys[actionKey]
}

// 保存设置
const saveSettings = async () => {
  try {
    // 更新hotkeys对象
    hotkeysData.value.forEach(item => {
      settings.hotkeys[item.actionKey] = item.key
    })
    
    // 保存设置到配置文件
    await window.electronAPI.saveSettings(settings)
    
    ElMessage.success('设置已保存')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  }
}

// 重置默认设置
const resetSettings = () => {
  settings.chromePath = ''
  settings.defaultUserDataDir = ''
  settings.defaultShortcutDir = ''
  settings.defaultWidth = 1024
  settings.defaultHeight = 768
  settings.defaultSpacing = 10
  settings.autoStartChrome = true
  settings.rememberWindowPositions = true
  settings.checkUpdates = true
  settings.hotkeys = {
    importWindows: 'Ctrl+I',
    closeAllWindows: 'Ctrl+Shift+C',
    arrangeWindows: 'Ctrl+Shift+A',
    startSync: 'Ctrl+Shift+S',
    stopSync: 'Ctrl+Shift+X'
  }
  
  // 更新快捷键数据
  hotkeysData.value.forEach(item => {
    item.key = settings.hotkeys[item.actionKey]
  })
  
  ElMessage.success('已恢复默认设置')
}

// 导出设置
const exportSettings = async () => {
  try {
    await window.electronAPI.exportSettings()
    ElMessage.success('设置已导出')
  } catch (error) {
    console.error('导出设置失败:', error)
    ElMessage.error('导出设置失败')
  }
}

// 导入设置
const importSettings = async () => {
  try {
    const importedSettings = await window.electronAPI.importSettings()
    if (importedSettings) {
      Object.assign(settings, importedSettings)
      
      // 更新快捷键数据
      hotkeysData.value.forEach(item => {
        item.key = settings.hotkeys[item.actionKey]
      })
      
      ElMessage.success('设置已导入')
    }
  } catch (error) {
    console.error('导入设置失败:', error)
    ElMessage.error('导入设置失败')
  }
}

// 加载设置
const loadSettings = async () => {
  try {
    const savedSettings = await window.electronAPI.getSettings()
    if (savedSettings) {
      Object.assign(settings, savedSettings)
      
      // 更新快捷键数据
      hotkeysData.value.forEach(item => {
        item.key = settings.hotkeys[item.actionKey]
      })
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

// 监听键盘事件捕获快捷键
const handleKeyboardEvent = (event: KeyboardEvent) => {
  if (!capturingShortcut.value) return
  
  event.preventDefault()
  
  const keys: string[] = []
  
  if (event.ctrlKey) keys.push('Ctrl')
  if (event.shiftKey) keys.push('Shift')
  if (event.altKey) keys.push('Alt')
  
  // 获取按下的非修饰键
  const key = event.key.toUpperCase()
  // 过滤掉修饰键本身
  const validKey = key !== 'CONTROL' && key !== 'SHIFT' && key !== 'ALT' && key !== 'META'
  
  if (validKey) {
    keys.push(key)
    
    if (keys.length >= 2) {
      const shortcut = keys.join('+')
      shortcutPreview.value = shortcut
      
      // 更新快捷键
      if (currentHotkeyIndex.value !== -1) {
        hotkeysData.value[currentHotkeyIndex.value].key = shortcut
      }
      
      // 延迟关闭对话框
      setTimeout(() => {
        shortcutDialogVisible.value = false
        stopCaptureShortcut()
      }, 1000)
    }
  }
}

onMounted(() => {
  loadSettings()
  window.addEventListener('keydown', handleKeyboardEvent)
})
</script>

<style lang="scss" scoped>
.settings {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .form-hint {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
  }
  
  .shortcut-capture {
    text-align: center;
    padding: 20px 0;
    
    .shortcut-preview {
      font-size: 24px;
      font-weight: bold;
      margin: 20px 0;
      padding: 10px;
      border: 2px dashed #dcdfe6;
      border-radius: 4px;
    }
    
    .shortcut-hint {
      font-size: 12px;
      color: #909399;
      margin-top: 10px;
    }
  }
}
</style>